package heima3_2.cn.osc.presenter;

import android.util.Log;

import java.io.File;
import java.io.IOException;

import heima3_2.cn.osc.model.re_interface.RetrofitInterface;
import heima3_2.cn.osc.utils.Global;
import heima3_2.cn.osc.utils.NetUtils;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

import static heima3_2.cn.osc.constant.Constants.baseUrl;

/**
 * Created by yaozhanlie on 2017/1/14.
 */

public abstract class BasePresenter<T> {


    private static final long DEFAULT_DIR_CACHE = 1024*1024;
    public Retrofit mRetrofit;
    protected final RetrofitInterface mRetrofitInterface;
    private OkHttpClient mClient;
    public Callback<T> mCallback = new Callback<T>() {
        @Override
        public void onResponse(Call<T> call, Response<T> response) {

            getSuccessData(response);
        }

        @Override
        public void onFailure(Call<T> call, Throwable t) {
            t.printStackTrace();
            getFailureData(t);
        }
    };
    /**
     * 访问网络之后失败的回调方法
     * */
    protected abstract void getFailureData(Throwable t);

    /**
     * 用retrofit访问网络之后成功的回调方法
     * @param response
     */
    protected abstract void getSuccessData(Response<T> response);

    public BasePresenter() {

        initOKHttp();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(mClient)
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .build();
        mRetrofitInterface = mRetrofit.create(RetrofitInterface.class);

    }

    /** 初始化OKHttp实现缓存 */
    private void initOKHttp() {
        File cacheDir = new File(Global.getContext().getCacheDir(),"openSourceChina");
        Log.d("bb",Global.getContext().getCacheDir()+"/openSourceChina");
        mClient = new OkHttpClient
                .Builder()
                .cache(new Cache(cacheDir, 10 * 1024 * 1024))
                .addInterceptor(mInterceptor)
                .build();

    }

    /** 缓存拦截器 */
    Interceptor mInterceptor = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetUtils.hasNetwork(Global.getContext())) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }

            okhttp3.Response response = chain.proceed(request);
            if (NetUtils.hasNetwork(Global.getContext())) {
                int maxAge = 60 * 60; // read from cache for 1 minute
                response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();
                System.out.println("aaaaa");
            } else {
                int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
                response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
                System.out.println("bbbb");
            }
            return response;
        }
    };

    /**
     * 子类Presenter需要继承这个方法，自己到RetrofitInterface里面写方法，获取Call<>,再调用CallBack
     * 传个int类型的参数是为了初始加载数据/下拉刷新或者上拉加载更多
     */
    public abstract void getData(int page);
}
